<?php
//
// XML网站地图生成插件
// 
// 
// Copyright 2018, 壹味科技
// http://www.evzg.com/
// 
// Author:TianQi,GaoYong
// Released on:2018-05-24
//
namespace plugins\evzg_sitemap\controller;

use cmf\controller\PluginAdminBaseController;
use app\portal\model\PortalCategoryModel;
use app\portal\model\PortalPostModel;
use think\Db;

class AdminIndexController extends PluginAdminBaseController
{

    protected function _initialize()
    {
        parent::_initialize();
        $adminId = cmf_get_current_admin_id();
        if (!empty($adminId)) {
            $this->assign("admin_id", $adminId);
        }
    }

    public function index()
    {
        $request = $this->request;
        $host = $request->domain();
        $this->assign("host", $host);
        return $this->fetch('/admin_index');
    }

    public function addxml1()
    {
        $site = $this->siteinfo();
        $html = '<a href="' . $site . '/">首页</a>';
        $lastmod = date('Y-m-d H:i:s', time());
        $xml = '<?xml version="1.0" encoding="utf-8"?><?xml-stylesheet type="text/xsl" href="' . $site . '/plugins/evzg_sitemap/evzg_sitemap.xsl"?><urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9" xmlns:mobile="http://www.google.com/schemas/sitemap-mobile/1.0"><url><loc>' . $site . '/</loc><changefreq>daily</changefreq><priority>1</priority><lastmod>' . $lastmod . '</lastmod></url>';

        // 输出分类
        $portalCategoryModel = new PortalCategoryModel();
        $category = $portalCategoryModel->where('status', 1)->where('delete_time', 0)->select();
        foreach ($category as $val) {
            $lastmod = date('Y-m-d H:i:s', time());
            $geturl = cmf_url('portal/List/index', 'id=' . $val['id'], "", true);
            $html .= '<a href="' . $geturl . '">' . $val['name'] . '</a>' . "<br>";
            $xml .= '<url><loc>' . $geturl . '</loc><changefreq>daily</changefreq><priority>0.8</priority><lastmod>' . $lastmod . '</lastmod></url>';
        }

        // 输出页面
        $PortalPostModel = new PortalPostModel();
        $where['post_status'] = '1';
        $where['post_type'] = '2';
        $article = $PortalPostModel->where($where)->where('delete_time', 0)->select();
        foreach ($article as $value) {
            $lastmod = date('Y-m-d H:i:s', time());
            $geturl = cmf_url('portal/Page/index', 'id=' . $value['id'], ".html", true);
            $html .= '<a href="' . $geturl . '">' . $value['post_title'] . '</a>' . "<br>";
            $xml .= '<url><loc>' . $geturl . '</loc><changefreq>monthly</changefreq><priority>0.5</priority><lastmod>' . $lastmod . '</lastmod></url>';
        }


        // 输出文章
        $where['post_status'] = '1';
        $where['post_type'] = '1';
        $article = $PortalPostModel->where($where)->where('delete_time', 0)->select();
        foreach ($article as $value) {
            $lastmod = date('Y-m-d H:i:s', $value['create_time']);

            // 设定分类查询条件
            $cidwhere['status'] = '1';
            $cidwhere['post_id'] = $value['id'];

            // 查询与文章匹配的分类
            $cid = Db::name('portal_category_post')->where($cidwhere)->select();

            // 假如一个文章有多个分类，在这里循环输出
            foreach ($cid as $v) {
                $geturl = cmf_url('portal/Article/index', array('id' => $value['id'], 'cid' => $v['category_id']), ".html", true);
                $html .= '<a href="' . $geturl . '">' . $value['post_title'] . '</a>' . "<br>";
                $xml .= '<url><loc>' . $geturl . '</loc><changefreq>monthly</changefreq><priority>0.5</priority><lastmod>' . $lastmod . '</lastmod></url>';
            }

        }
        $xml .= '</urlset>';
        $this->updatexml($xml);
        $this->success("生成成功！！");
    }


    private function siteinfo()
    {
        $request = $this->request;
        return $request->domain();
    }

    private function updatetxt($data)
    {
        $this->writefile('txt', $data);
    }

    private function updatexml($data)
    {
        $this->writefile('xml', $data);
    }

    private function writefile($type, $data)
    {
        $myfile = fopen($_SERVER['DOCUMENT_ROOT'] . "/sitemap." . $type, "w") or die("Unable to open file!");
        fwrite($myfile, $data);
        fclose($myfile);
    }


    //****************************** 重构xml 支持大文件   ***************************************//
    /* author@zhou
     * 功能：生成地图文件
     * return
     */
    public function addxml()
    {
        //列表
        //文章
        //标签大全
        //搜索大全 暂未做
        $site = $this->siteinfo();
        $xml = "<?xml version='1.0' encoding='UTF-8'?>\n";
        $xml .= "<sitemapindex>\n";
        $xml .= "<sitemap>\n";

        $catData = $this->cateData();
        $catData = $this->createXmls($catData,"monthly","cate");


        $articleData = $this->articleData();
        $articleData =$this->createXmls($articleData,"daily","article");

        $tagData = $this->tagData();
        $tagData =$this->createXmls($tagData,"daily","tag");

        $date = date("Y-m-d");
        foreach($catData as $k=>$v){
            $xml.="<loc>{$site}{$v}</loc>\n";
            $xml.="<lastmod>{$date}</lastmod>\n";
        }
        foreach($articleData as $k=>$v){
            $xml.="<loc>{$site}{$v}</loc>\n";
            $xml.="<lastmod>{$date}</lastmod>\n";
        }

        foreach($tagData as $k=>$v){
            $xml.="<loc>{$site}{$v}</loc>\n";
            $xml.="<lastmod>{$date}</lastmod>\n";
        }
        $xml .= "</sitemap>\n";
        $xml .= "</sitemapindex>\n";

        file_put_contents($_SERVER['DOCUMENT_ROOT'] . "/sitemap.xml",$xml);

        $this->success("生成成功！！");

    }

    /* author@zhou
     * 功能：分类数据
     * return
     */
    public function cateData()
    {
        $site = $this->siteinfo();
        $lastmod = date('Y-m-d H:i:s', time());
        $priority = 0.8;
        $result[] = ['url' => $site, 'name' => "首页", "lastmod" => $lastmod, "priority" => $priority];
        $portalCategoryModel = new PortalCategoryModel();
        $category = $portalCategoryModel->field("id,name")->where('status', 1)->where('delete_time', 0)->select();
        foreach ($category as $val) {
            $geturl = cmf_url('portal/List/index', 'id=' . $val['id'], "", true);
            $result[] = ["url" => $geturl, "name" => $val['name'], "lastmod" => $lastmod, "priority" => $priority];
        }
        return $result;
    }


    /* author@zhou
     * 功能：文章数据
     * return 
     */
    public function articleData()
    {
        // 输出文章
        $where['post_status'] = '1';
        $where['post_type'] = '1';
        $PortalPostModel = new PortalPostModel();
        $article = $PortalPostModel->field("id,post_title,create_time")->where($where)->where('delete_time', 0)->select();
        $result = [];
        $priority = 0.8;
        foreach ($article as $value) {
            $lastmod = date('Y-m-d H:i:s', $value['create_time']);
            $cidwhere['status'] = '1';
            $cidwhere['post_id'] = $value['id'];
            // 查询与文章匹配的分类
            $cid = Db::name('portal_category_post')->where($cidwhere)->select();
            // 假如一个文章有多个分类，在这里循环输出
            foreach ($cid as $v) {
                $geturl = cmf_url('portal/Article/index', array('id' => $value['id'], 'cid' => $v['category_id']), ".html", true);

                $result[] = ['url' => $geturl, 'name' => $value['post_title'], "lastmod" => $lastmod, "priority" => $priority];
            }

        }

        return $result;
    }


    /* author@zhou
     * 功能：标签数据
     * return 
     */
    public function tagData()
    {
        $model = new \app\portal\model\PortalTagModel();
        $http_type = ((isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] == 'on') || (isset($_SERVER['HTTP_X_FORWARDED_PROTO']) && $_SERVER['HTTP_X_FORWARDED_PROTO'] == 'https')) ? 'https://' : 'http://';
        $host = $http_type . $_SERVER['SERVER_NAME'] . '/';
        $routeModel = new \app\portal\model\RouteModel();
        $priority = 0.5;
        $result = [];
        $lastmod = date('Y-m-d H:i:s', time());
        $row = $routeModel->where(array("status" => 1, "full_url" => "portal/Tag/index"))->find();
        $data = $model->field("id,name")->where(array("status" => 1))->order("id desc")->select();
        foreach ($data as $k => $v) {
            $real_url = str_replace(":id", $v['id'], $row['url']);
            $real_url = $host . $real_url . ".html";
            $result[] = ['url' => $real_url, 'name' => $v['name'], "lastmod" => $lastmod, "priority" => $priority];
        }
        return $result;
    }

    /* author@zhou
     * 功能：生成xml
     * @data array  数据
     * @path string 保存地址名称
     * return
     */
    public function createXmls($data,$daily = "daily", $path = '')
    {
        $limit = 2;
        $xml = "<?xml version='1.0' encoding='utf-8'?>\n";
        $xml .= "<urlset>\n";
        $footer = "</urlset>\n";
        $num = 1;
        $returnUrl = [];
        if(count($data) > $limit){
            $num = ceil(count($data) / $limit);
        }
        for($i=1;$i<=$num;$i++){
            $length = $limit;
            if($i == $num){
                $length = count($data) - ($num-1)*$limit;
            }
            $result = array_slice($data,($i-1)*$limit,$length);
            $xmlUrl = '';
            foreach($result as $k=>$v){
                $xmlUrl .= "<url>\n";
                $xmlUrl .= "<loc>{$v['url']}</loc>\n";
                $xmlUrl .= "<lastmod>{$v['lastmod']}</lastmod>\n";
                $xmlUrl .= "<changefreq>{$daily}</changefreq>\n";
                $xmlUrl .= "<priority>{$v['priority']}</priority>\n";
                $xmlUrl .= "</url>\n";
            }
            $html = $xml.$xmlUrl.$footer;
            if($i > 1){
                $realPath = "/sitemap/".$path."_{$i}".'.xml';
                file_put_contents($_SERVER['DOCUMENT_ROOT'] . $realPath,$html);
            }else{
                $realPath = "/sitemap/".$path.'.xml';
                file_put_contents($_SERVER['DOCUMENT_ROOT'] . $realPath,$html);
            }
            $returnUrl[] = $realPath;
        }

        return $returnUrl;
    }

}
